package main

import (
	"context"
	"fmt"
	"github.com/coreos/etcd/clientv3"
	"time"
)

//对key增加一个过期时间，这这情况在实现分布式的乐观锁很常用。比如一台机器挂了，这个机器上的锁需要释放。所以锁需要生命期管理
func main() {

	var (
		config             clientv3.Config
		client             *clientv3.Client
		err                error
		lease              clientv3.Lease
		leaseGrantResponse *clientv3.LeaseGrantResponse

		putResponse *clientv3.PutResponse
		getResponse *clientv3.GetResponse

		kv clientv3.KV
	)

	config = clientv3.Config{
		Endpoints:   []string{"10.70.30.73:2379"},
		DialTimeout: 3 * time.Second,
	}

	if client, err = clientv3.New(config); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("hello,etcd  ")

	kv = clientv3.NewKV(client)
	lease = clientv3.NewLease(client)

	if leaseGrantResponse, err = lease.Grant(context.TODO(), 10); err != nil {
		fmt.Println(err)
		return
	}

	leaseID := leaseGrantResponse.ID

	//key 与lease Id 关联，用option的WithLease，一般情况是为了程序异常或者机器挂掉，防止锁一直被占用。一般情况是定时续租。
	if putResponse, err = client.KV.Put(context.TODO(), "/cron/lock/job1", "value", clientv3.WithLease(leaseID)); err != nil {
		fmt.Println(err)
		return
	} else {
		fmt.Println("写入成功", putResponse.Header.String())
	}

	// 检查key是否过期
	for {
		if getResponse, err = kv.Get(context.TODO(), "/cron/lock/job1"); err != nil {
			fmt.Println(err)
			return
		} else {
			if getResponse.Count == 0 {
				fmt.Println("已经过期，结束")
				break
			} else {
				fmt.Println("还没过期,过2s再看你", getResponse.Kvs)
				time.Sleep(2 * time.Second)
			}
		}
	}
	//输出如下
	//hello,etcd
	//写入成功 cluster_id:14841639068965178418 member_id:10276657743932975437 revision:117 raft_term:3
	//还没过期,过2s再看你 [key:"/cron/lock/job1" create_revision:117 mod_revision:117 version:1 value:"value" lease:7587845480017428903 ]
	//还没过期,过2s再看你 [key:"/cron/lock/job1" create_revision:117 mod_revision:117 version:1 value:"value" lease:7587845480017428903 ]
	//还没过期,过2s再看你 [key:"/cron/lock/job1" create_revision:117 mod_revision:117 version:1 value:"value" lease:7587845480017428903 ]
	//还没过期,过2s再看你 [key:"/cron/lock/job1" create_revision:117 mod_revision:117 version:1 value:"value" lease:7587845480017428903 ]
	//还没过期,过2s再看你 [key:"/cron/lock/job1" create_revision:117 mod_revision:117 version:1 value:"value" lease:7587845480017428903 ]
	//还没过期,过2s再看你 [key:"/cron/lock/job1" create_revision:117 mod_revision:117 version:1 value:"value" lease:7587845480017428903 ]
	//已经过期，结束
	//
	//Process finished with exit code 0

}
